<?php
// $Id$

/**
 * @file
 * 
 */

/**
 * Form builder; Builds a form to change general settings for this module.
 */
function wow_admin_settings() {
  module_load_include('inc', 'wow', 'includes/wow.player');
  
  $form = array();
  
  $form['settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('World of Warcraft settings'),
    '#collapsible' => FALSE
  );
  
  $form['settings']['wow_faction'] = array(
    '#type' => 'select',
    '#title' => t('Guild faction'),
    '#options' => array(
      WarcraftPlayer::FACTION_ALLIANCE => t('Alliance'),
      WarcraftPlayer::FACTION_HORDE    => t('Horde')
    ),
    '#default_value' => variable_get('wow_faction', WarcraftPlayer::FACTION_ALLIANCE)
  );
  
  // @todo Rename setting to 'Battle.net region' and variable to 'wow_bnet_region'?
  $form['settings']['wow_armory_region'] = array(
    '#type' => 'select',
    '#title' => t('Armory region'),
    '#description' => t("The armory service used to import information. Set to your server's location."),
    '#options' => array(
      'us' => t('US and Oceanic'),
      'eu' => t('Europe'),
      'kr' => t('South Korea'),
      'cn' => t('China'),
      'tw' => t('Taiwan')
    ),
    '#default_value' => variable_get('wow_armory_region', 'us')
  );
  
  $form['settings']['wow_power_script'] = array(
    '#type' => 'select',
    '#title' => t('Power script'),
    '#description' => t('Item links will show details from this database service when hovered over. The link and provider domains must match for this to work.'),
    '#options' => array(
      WOW_SCRIPT_NONE     => 'None',
      WOW_SCRIPT_WOWHEAD  => 'Wowhead',
      WOW_SCRIPT_THOTTBOT => 'Thottbot',
      WOW_SCRIPT_MMOCHAMPION => 'MMO-Champion'
    ),
    '#default_value' => variable_get('wow_power_script', WOW_SCRIPT_NONE)
  );
  
  // @todo Experimental Wowhead script options.
  //$form['settings']['wowhead_options'] = array(
  //  '#type' => 'fieldset',
  //  '#title' => t('Wowhead script options'),
  //  '#collapsible' => TRUE,
  //  '#collapsed' => TRUE
  //);
  
  //$form['settings']['wowhead_options']['wow_wowhead_profile_links'] = array(
  //  '#type' => 'checkbox',
  //  '#title' => t('Link profiles to Wowhead where applicable'),
  //  '#description' => t('EXPERIMENTAL'),
  //  '#default_value' => variable_get('wow_wowhead_profile_links', FALSE)
  //);
  
  return system_settings_form($form);
}

/**
 * Menu callback; Present an armory import page.
 */
function wow_admin_import_page($op = NULL) {
  return drupal_get_form('wow_admin_import_form');
}

// @todo Add character info import and change form controls.
function wow_admin_import_form() {
  $form['armory_import'] = array(
    '#type' => 'submit',
    '#value' => t('Import from armory'),
    '#validate' => array('wow_admin_import_validate'),
    '#submit' => array('wow_admin_import_submit')
  );
  
  return $form;
}

/**
 * Validate certain guild variables prior to an import.
 */
function wow_bnet_guild_import_validate($form, &$form_state) {
  // We cannot perform a guild import without a set game server and guild name.
  $t_args = array('@settings-link' => url('admin/guild/settings'));
  
  $server = variable_get('guild_game_server', '');
  if (empty($server)) {
    form_set_error('armory_import', t('The <a href="@settings-link">game server field</a> is required to import armory data.', $t_args));
  }
  
  $name = variable_get('guild_guild_name', '');
  if (empty($name)) {
    form_set_error('armory_import', t('The <a href="@settings-link">guild name field</a> is required to import armory data.', $t_args));
  }
}

/**
 * Start the import process.
 */
function wow_bnet_guild_import_submit($form, &$form_state) {
  drupal_goto('admin/guild/wow/import-guild/confirm');
}

/**
 * Menu callback; Present an armory import confirm message.
 *
 * @see wow_armory_import_guild_confirm()
 */
function wow_armory_import() {
  return drupal_get_form('wow_armory_import_guild_confirm');
}

/**
 * Explain the import process and then make sure the administrator wants to continue.
 *
 * @see wow_armory_import_guild_confirm_submit()
 */
function wow_armory_import_guild_confirm(&$form_state) {
  $form = array();
  
  return confirm_form($form, t('Are you sure you want to continue?'), 'admin/guild/wow',
    '<p>' .
    t('This will import guild data from the World of Warcraft Armory. ' .
    'If an existing player is found, some data may be modified. ' .
    'If a player is found to no longer be in your guild, they will not be deleted, however their status will be changed to <em>hidden</em>. ' .
    'Player ranks will also be modified accordingly.') .
    '</p>' .
    '<p>' . t('This action cannot be undone.') . '</p>',
    t('Import'), t('Cancel'));
}

/**
 * Execute the armory guild import operation.
 *
 * @see armory_batch_import_guild()
 */
function wow_armory_import_guild_confirm_submit($form, &$form_state) {
  module_load_include('inc', 'wow', 'includes/wow.armory');
  
  $realm  = variable_get('guild_game_server', '');
  $name   = variable_get('guild_guild_name', '');
  $region = variable_get('wow_armory_region', 'us');
  
  armory_batch_import_guild($realm, $name, $region);
  
  $form_state['redirect'] = 'admin/guild/wow';
}

// @todo Remove deprecated armory import functions above this line and rename new functions accordingly.

/**
 *
 */
function wow_admin_form() {
  $realm_name = variable_get('guild_game_server', '');
  $guild_name = variable_get('guild_guild_name', '');
  
  module_load_include('inc', 'wow', 'includes/wow.import');
  $region = variable_get('wow_armory_region', 'us');
  $bnet_locale = wow_get_bnet_locale();
  $default_language = language_default();
  
  $description = '<p>'. t('Automatically add, remove, and update players from your guild roster using the Battle.net armory.') . '</p>';
  if (empty($realm_name) || empty($guild_name)) {
    $description .= '<p>' . t('<strong class="error">The realm and guild name fields must be set before you can start an import.</strong>') . '</p>';
  }
  if ($bnet_locale['language'] != $default_language->language) {
    $region_names = array(
      'us' => t('US and Oceanic'),
      'eu' => t('European'),
      'kr' => t('Korean')
    );
    $bnet_language = ($bnet_locale['language'] == 'en') ? t('English') : t('Korean');
    $t_args = array('%region' => $region_names[$region], '%site-language' => $default_language->native, '%armory-language' => $bnet_language);
    $description .= '<p>' . t('<strong class="warning">The %region armory does not support the default site language (%site-language). The default armory language (%armory-language) will be used instead.</strong>', $t_args) . '</p>';
    //$description .= '<p>' . t('<strong class="warning">The armory region in use does not support the language being used on this site. The default armory language for this region will be used instead.</strong>') . '</p>';
  }
  
  $form['bnet_import_guild'] = array(
    '#type' => 'fieldset',
    '#title' => t('Import guild from Battle.net'),
    '#description' => $description,
    '#collapsible' => FALSE
  );
  
  $form['bnet_import_guild']['start_roster_import'] = array(
    '#type' => 'submit',
    '#value' => t('Start roster import'),
    '#disabled' => $missing_names,
    '#validate' => 'wow_bnet_guild_import_validate',
    //'#submit' => ''
  );
  
  // @todo Remove me.
  module_load_include('inc', 'wow', 'includes/wow.import');
  //wow_import_bnet_guild_roster('medivh', 'emergence');
  //wow_import_bnet_realm_status(array('medivh', 'ptr'));
  wow_import_wowprogress_rankings('Trismegistus', 'Medivh');
  
  return $form;
}

/**
 *
 */
function wow_item_import_form() {
  $powered_by = variable_get('wow_power_script', WOW_SCRIPT_NONE);
  if ($powered_by == WOW_SCRIPT_NONE) {
    $t_args = array('@script-provider' => url('admin/guild/settings/wow'));
    drupal_set_message(t('Setting a <a href="@script-provider">power script provider</a> before importing items is strongly recommended.', $t_args), 'warning', FALSE);
  }
  
  $form['item'] = array(
    '#type' => 'textfield',
    '#title' => t('Item ID'),
    '#description' => t('Enter the item ID number or an item link from a power script provider.'),
    '#default_value' => '',
  //'#size' => 6,
  //'#maxlength' => 5,
    '#required' => TRUE
  );
  
  // @todo Implement item importing from the PTR.
  //$form['ptr'] = array(
  //  '#type' => 'checkbox',
  //  '#title' => t('Attempt import from PTR servers'),
  //  '#default_value' => FALSE
  //);
  
  $form['import']= array(
    '#type' => 'submit',
    '#value' => t('Import')
  );
  
  return $form;
}

function wow_item_import_form_validate($form, &$form_state) {
  $item = $form_state['values']['item'];
  
  if (!is_numeric($item)) {
    // Check if the item link provided is valid.
    if (!valid_url($item)) {
      form_set_error('item', t('You must specify a valid URL.'));
      return;
    }
    
    // @todo Should the host be checked, perhaps using parse_url()?
    
    // Get the item id number out of the URL. This expression is quite forgiving
    // and will actually match a wide range of database site URLs, including
    // Blizzard's new BNET site.
    preg_match('@/i(?:tem)?(?:=|/)(?P<item>\d+)@i', $item, $matches);
    
    if (!isset($matches) || !isset($matches['item'])) {
      form_set_error('item', t('An item could not be determined from the given URL. ' .
        'Please use a link from a supported power script provider.'));
      return;
    }
    
    $item = $matches['item'];
  }
  
  // Check for blatently wrong item id numbers.
  if ($item < 1) {
    form_set_error('item', t('The item ID was invalid.'));
  }
  else {
    $form_state['values']['item'] = $item;
  }
}

function wow_item_import_form_submit($form, &$form_state) {
  module_load_include('inc', 'wow', 'includes/wow.import');
  
  wow_import_item($form_state['values']['item']);
}
